import {
	ref
} from "vue";
import useComment from "./useComment.js";
import useLoginTodo from "@/composition/useLoginTodo.js";

export default function useCommentInteraction(articleData, userInfo, $http) {
	const showPopup = ref(false);
	const replyData = ref([]);
	const commentList = ref([]);
	let commentUtils = null;

	// 初始化评论工具
	const initCommentUtils = async () => {
		if (!articleData.value?._id) {
			throw new Error("文章ID不存在");
		}

		commentUtils = useComment({
				articleId: articleData.value._id,
			},
			$http
		);
		await commentUtils._getCommentList();
		commentList.value = commentUtils.list.value;
	};

	// 打开评论弹窗
	const openCommentPopup = async () => {
		const loginTodo = useLoginTodo(userInfo);
		const ok = await loginTodo.checkedisLogin();
		if (!ok) return;
		showPopup.value = true;
	};

	// 发送评论数据
	const sendCommentData = async (content) => {
		try {
			const {
				msg
			} = await $http.update_comment({
				userId: userInfo._id,
				articleId: articleData.value._id,
				content,
				...replyData.value,
			});

			uni.showToast({
				title: msg,
				icon: "success",
			});

			showPopup.value = false;
			replyData.value = [];

			// 重新获取评论数据
			await commentUtils._getCommentList();
			commentList.value = commentUtils.list.value;
		} catch (error) {
			console.error("发送评论失败", error);
			uni.showToast({
				title: "发送失败",
				icon: "none",
			});
		}
	};

	// 处理评论回复
	const handleCommentReply = (data) => {
		replyData.value = {
			comment_id: data.comment.comment_id,
			is_reply: data.isReply,
		};

		// 扩展回复Id
		if (data.comment.comment_id) {
			replyData.value.reply_id = data.comment.reply_id;
		}

		openCommentPopup();
	};

	// 关闭评论弹窗
	const closeCommentPopup = (value) => {
		showPopup.value = value;
	};

	return {
		showPopup,
		commentList,
		initCommentUtils,
		openCommentPopup,
		sendCommentData,
		handleCommentReply,
		closeCommentPopup,
	};
}